package ed.hbut.supermarket1.service.impl;

import ed.hbut.supermarket1.mapper.CategoryMapper;
import ed.hbut.supermarket1.mapper.MerchandiseMapper;
import ed.hbut.supermarket1.entity.Merchandise;
import ed.hbut.supermarket1.service.MerchandiseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class MerchandiseServiceImpl implements MerchandiseService {

    @Autowired
    public MerchandiseMapper merchandiseMapper;

    @Autowired
    public CategoryMapper categoryMapper;

    @Transactional//事务管理
    @Override
    public void postmechandise(Merchandise merchandise) {

        System.out.println("service postmechandise");

        //给商品分类赋值
        String name= merchandiseMapper.getCategoryName(merchandise.getMerchandiseCategoryId());
        merchandise.setMerchandiseCategoryName(name);

        //增加商品，该分类的数量加一
        categoryMapper.CategoryAddOne(merchandise.getMerchandiseCategoryId());
        merchandiseMapper.insertMerchandise(merchandise);
    }

    @Override
    public List<Merchandise> getAllMerchandise() {

        return merchandiseMapper.getAllMerchandise();
    }

    @Override
    public Merchandise getById(Integer id) {

        return merchandiseMapper.getById(id);
    }

    @Transactional//事务管理
    @Override
    public void deleteById(Integer id) {

        Integer categoryId= merchandiseMapper.getCategoryId(id);

        merchandiseMapper.deleteById(id);

        //调用分类的mapper接口，删除一个商品，数量减一
        categoryMapper.deleteMerchandiseSubtractOne(categoryId);
    }

    @Override
    public void update(Merchandise merchandise) {

        //原来的分类id -1

        Integer categoryId= merchandiseMapper.getCategoryId(merchandise.getMerchandiseId());
        categoryMapper.deleteMerchandiseSubtractOne(categoryId);
        //新增的id加1
        categoryMapper.CategoryAddOne(merchandise.getMerchandiseCategoryId());
         String name =  merchandiseMapper.getCategoryName(merchandise.getMerchandiseCategoryId());
        merchandise.setMerchandiseCategoryName(name);
        merchandiseMapper.update(merchandise);
    }
}
